package bean;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import oracle.jdbc.OracleConnection.CommitOption;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

public class B01boardDTO {

	public ArrayList<B01boardVO> al;
	private B01boardVO vo=null;		// 1. vo 변수와 connection 변수
	Connection conn = null;
									// 2. 페이징을 위한 변수 
	int listSize = 10;	// 페이지당 표시되는 행수  
	int blockSize = 3;	// 한 블럭당 표시되는 페이지수 
	int totSize = 0;	// 전체 게시물의 갯수
	int totPage = 0;	// 현재 페이지  
	int totBlock = 0; 	// 전체 블럭수
	int nowPage = 1;	// 현재 페이지 
	int nowBlock = 1;	// 현재 블럭
	int startNo = 0; 	// 리스트 목록의 시작 위치 
	int endNo = 0; 		// 리스트 목록의 끝 위치 
	int startPage = 0; 	// 현재 블럭에서 표시되는 시작 블럭번호
	int endPage = 0;	// 현재 블럭에서 표시되는 끝 블럭 번호 
	
//	String saveDir="D:/jsy/kiSunnyShop/WebContent/memberPhoto_B/";
	String saveDir="F:/자바/학원/and_1406/2/kiSunnyShop/WebContent/memberPhoto_B/";
	
	public B01boardDTO() {			// 3. 생성자에서 conn 처리 
		conn = new MyOracle().getConn();
	}
	
//	public B01boardDTO(){
//	try{
//		Context init = new InitialContext();
//		DataSource ds = (DataSource)init.lookup("java:comp/env/jdbc/OracleDB");
//		conn = ds.getConnection();
//		System.out.println("<h3>연결에 성공하였습니다</h3>");
//
//	}catch(Exception e){
//		System.out.println("<h3>연결에 실패하였습니다</h3>");
//		e.printStackTrace();
//	}
//	
//	}
	

	public boolean insert(){		// 4. 입력을 위한 처리 
		boolean b= false;
//		String sql = "insert into board01(m_id, b_pw, b_date, b_modifyDate, b_title, b_content, b_number, b_image, b_prno, b_group, b_deep,che) "
//				+ " values(?,  ?, sysdate,sysdate, ?, ?, seq_board01_b_number.nextval, ?, 0,seq_board01_b_group.nextval , seq_board01_b_deep.nextval,0)";
		
		String sql = "insert into board01(m_id, b_pw, b_date, b_modifyDate, b_title, b_content, b_number, b_image, b_prno, b_group, b_deep,che) "
				+ " values(?,  ?, sysdate,sysdate, ?, ?, seq_board01_b_number.nextval, ?, 1,seq_board01_b_number.currval , 0,0)";
		
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getM_id());
			pst.setString(2, vo.getB_pw());
			pst.setString(3, vo.getB_title());
			pst.setString(4, vo.getB_content());
			pst.setString(5, vo.getB_image());
		
		
			int cnt = pst.executeUpdate();
			if (cnt>0) b=true;
			
			pst.close();
//			conn.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
	
	public boolean thum(){
		boolean flag = false;
		try {
			String sql="update board01 set thumb=b_image where b_image= ?";
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getB_image());
			int cnt = pst.executeUpdate();
			flag = true;
			System.out.println("업데이트 완료");
			pst.close();
//			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return flag;
	}
	
	
    public void page(){				// 5. 페이지 처리 
    	String sql = "select count(*) cnt from board01 where b_number like ?";
    	try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%"+vo.getFind()+"%");
//			pst.setString(2, "%"+vo.getFind()+"%");
			ResultSet rs = pst.executeQuery();
			if(rs.next()){
			totSize = rs.getInt("cnt"); 
			// 전체 페이지수 
			totPage = (int)Math.ceil(totSize*1.0/listSize);
			// 전체 블럭수
			totBlock = (int)Math.ceil(totPage*1.0/blockSize);
			// 현재블럭
			nowBlock = (int)Math.ceil(nowPage*1.0 / blockSize);
			// 페이지의 시작과 끝 번호 
			endPage = nowBlock * blockSize;
			startPage = endPage-blockSize+1;
			// 게시물의 시작번호와 끝 번호
			endNo = nowPage * listSize;
			startNo = endNo-listSize + 1;
			// endPage, endNo 보정값
			if(endPage > totPage) endPage = totPage;
			if(endNo>totSize) endNo = totSize;
			}
			System.out.println("<li>totSize=" + totSize);
			System.out.println("<li>totPage=" + totPage);
			
//			rs.close();
//			pst.close();
			
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
	}
	
	public ArrayList<B01boardVO> select(){	// 6. 검색과 리스트를 위한 처리
		page();
		ArrayList<B01boardVO> al = new ArrayList<B01boardVO>();
		
		String sql = "select * from(select rownum rn, a.* from"
				+ "(select * from board01 where m_id like ? or b_title like ? "
				+ "or b_content like ? order by b_group desc, b_prno)a)"
				+ " where rn between ? and ?";
	
		/*
		 * String sql = "select * from ("
				+ " select rownum rn, c.*from("
				+ " select * from board01 "
				+ " where m_id like ? or b_title like ? or b_content like ? order by b_number desc)c"
				+ " )b"
				+ " where b.rn between ? and ? ";
		*/
		try{
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, "%" + vo.getFind() + "%");
			pst.setString(2, "%" + vo.getFind() + "%");
			pst.setString(3, "%" + vo.getFind() + "%");
			pst.setInt(4, startNo);
			pst.setInt(5, endNo);			
			ResultSet rs = pst.executeQuery();
			while(rs.next()){
				B01boardVO v = new B01boardVO();
				v.setB_number(rs.getInt("b_number"));
				v.setB_title(rs.getString("b_title"));
				v.setB_date(rs.getString("b_date"));
				v.setM_id(rs.getString("m_id"));
				v.setB_content(rs.getString("b_content"));
				v.setB_image(rs.getString("b_image"));
				v.setChe(rs.getInt("che"));
				v.setB_prno(rs.getInt("b_prno"));
				al.add(v);
			}
			rs.close();
			pst.close();
			conn.close();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return al;
	}
	
	public B01boardVO selectOne(){			// 7. view를 위한 처리 
		B01boardVO v = new B01boardVO();
		String sql = "select * from board01 where b_number=?";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			System.out.println(vo.getB_number());
			pst.setInt(1, vo.getB_number());
			ResultSet rs = pst.executeQuery();
			while(rs.next()){
				v.setB_number(rs.getInt("b_number"));
				v.setB_title(rs.getString("b_title"));
				v.setM_id(rs.getString("m_id"));
				v.setB_date(rs.getString("b_date"));
				v.setB_modifyDate(rs.getString("b_modifyDate"));
				v.setB_content(rs.getString("b_content"));
				v.setB_image(rs.getString("b_image"));
				v.setB_deep(rs.getInt("b_deep"));
				v.setB_group(rs.getInt("b_group"));
				v.setB_prno(rs.getInt("b_prno"));
			}
			rs.close();
			pst.close();
//			conn.close();
		} catch (Exception e) {

		}
		return v;
	}

	public boolean review()
	{
		boolean b=false;
		
		String sql="update BOARD01 set che = nvl(che,0)+1 where B_NUMBER = ?";
		try
		{			
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setInt(1, vo.getB_number());
			System.out.println("rno "+vo.getB_number());
			int cnt = pst.executeUpdate();
			b=true;
			pst.close();
			conn.close();
			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}		
		return b;		
	}
	
	
	public boolean delete(){			// 8. 삭제를 위한 처리 
		System.out.println(vo.getB_image());
		boolean b = false;
		String sql = "delete from board01 where b_number=?";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setInt(1, vo.getB_number());
			int cnt = pst.executeUpdate();
			System.out.println(vo.getB_image());
			if(cnt>0) b=true;
				File f = new File(saveDir + vo.getB_image());
				if(f.exists()) f.delete();
			pst.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return b;
	}
	
	public boolean modify(){			// 9. 수정을 위한 처리 
		boolean b=false;
		String sql = "update board01 set m_id=?, b_pw=?, b_modifyDate=sysdate, b_title=?, b_content=?, b_image=? where b_number = ?";
		try {
			PreparedStatement pst =conn.prepareStatement(sql);
			pst.setString(1, vo.getM_id());
			pst.setString(2, vo.getB_pw());
			pst.setString(3, vo.getB_title());
			pst.setString(4, vo.getB_content());
			pst.setString(5, vo.getB_image());
			pst.setInt(6, vo.getB_number());
			int cnt = pst.executeUpdate();
			if (cnt>0) b=true;
			
			pst.close();
			conn.close();
				
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
	
	public B01boardVO getVo() {
		return vo;
	}

	public void setVo(B01boardVO vo) {
		this.vo = vo;
		this.nowPage = vo.getNowPage();
		this.nowBlock = vo.getNowBlock();
		
	}

	
	public void file(B01boardVO vo){
		this.vo = vo;
		// 파일 처리 
		int size =1024*1024*10; /* 파일사이즈 */
			
			String oriFile="";
			String sysFile=""; 
			MultipartRequest multi = null;
			try{
				multi = new MultipartRequest(vo.getRequest(), saveDir, size, "utf-8", new DefaultFileRenamePolicy());
				
				Enumeration files = multi.getFileNames();
				String tempFile = (String)files.nextElement();
	
				oriFile = multi.getOriginalFileName(tempFile);
				sysFile = multi.getFilesystemName(tempFile);
				
				vo.setM_id(multi.getParameter("m_id"));						//데이터 베이스에 저장
				vo.setB_pw(multi.getParameter("b_pw"));
				vo.setB_title(multi.getParameter("b_title"));
				vo.setThumb(multi.getParameter("thumb"));
				vo.setB_content(multi.getParameter("b_content"));

				vo.setB_number(Integer.parseInt(multi.getParameter("b_number")));	// request는 String값만 받으므로, 숫자로 변환해준다. 
				if(sysFile == null || sysFile.equals("")){ 					// 수정시, 파일을 변경하지 않으면 원래 이미지가 나오게 한다. 
					vo.setB_image(multi.getParameter("b_oriImage"));
				}
				else{
					vo.setB_image(sysFile);									// 처음에 입력하거나, 수정시, 새 이미지가 나오게 한다. 
					// 섬네일 파일 추가 생성 (썸네일 안나올거면 안주면 됨) 
					ParameterBlock pd = new ParameterBlock();
					pd.add(saveDir + sysFile);
					RenderedOp rOp = JAI.create("fileload", pd);
					BufferedImage bi = rOp.getAsBufferedImage();
					BufferedImage thumb = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
					Graphics2D g = thumb.createGraphics();
					g.drawImage(bi, 0, 0, 100, 100, null);
					
					File file = new File(saveDir + "sm_" + sysFile);
					ImageIO.write(thumb,"png", file);
				}	
				vo.setB_group(Integer.parseInt(multi.getParameter("b_group")));
				vo.setB_deep(Integer.parseInt(multi.getParameter("b_deep")));
				vo.setB_prno(Integer.parseInt(multi.getParameter("b_prno")));
			}catch(Exception ex){
				ex.printStackTrace();
			}		
			 try {
		        	
		            //썸네일 가로사이즈
		            int thumbnail_width = 80;
		            //썸네일 세로사이즈
		            int thumbnail_height = 80;
//		            
//		            for(int i = 1; i <= 18; i++ ){
//		            	photo = "s" + i + ".jpg";
		            	//원본이미지파일의 경로+파일명
		            	File origin_file_name = new File("F:/자바/학원/and_1406/2/kiSunnyShop/WebContent/memberPhoto_B/"+vo.getB_image());
		            	File thumb_file_name = new File("F:/자바/학원/and_1406/2/kiSunnyShop/WebContent/thumb_B/"+vo.getB_image());
		            
//			            File origin_file_name = new File("D:/jsy/kiSunnyShop/WebContent/memberPhoto_B/"+vo.getB_image());
//			            File thumb_file_name = new File("D:/jsy/kiSunnyShop/WebContent/thumb_B/"+vo.getB_image());
			     
			            BufferedImage buffer_original_image = ImageIO.read(origin_file_name);
			            BufferedImage buffer_thumbnail_image = new BufferedImage(thumbnail_width, thumbnail_height, BufferedImage.TYPE_3BYTE_BGR);
			            Graphics2D graphic = buffer_thumbnail_image.createGraphics();
			            graphic.drawImage(buffer_original_image,0 , 0, thumbnail_width, thumbnail_height, null);
			            ImageIO.write(buffer_thumbnail_image, "jpg", thumb_file_name);
			        
			            System.out.println("썸네일 생성완료");
//		            }
		        } catch (Exception e) {
		            e.printStackTrace();
		        }  
	}

	public boolean replyInput(){
		boolean b = false;
//		String sql = "insert into board01(m_id, b_pw, b_date, b_modifyDate, "
//				+ "b_title, b_content, b_number, b_image, b_prno, b_group, b_deep) "
//				+ " values(?, ?, sysdate , sysdate, "
//				+ " ?, ?, seq_board01.nextval, ?, ?, ?, ? || '-' || seq_board01.nextval)";
		
		String sql = "insert into board01(m_id, b_pw, b_date, b_modifyDate, "
				+ "b_title, b_content, b_number, b_image, b_prno, b_group, b_deep,che) "
				+ " values(?, ?, sysdate , sysdate, "
				+ " ?, ?, seq_board01_b_number.nextval, ?, 2, ?, 1,0)";
		
		
		
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, vo.getM_id());
			pst.setString(2, vo.getB_pw());
			pst.setString(3, vo.getB_title());
			pst.setString(4, vo.getB_content());
			pst.setString(5, vo.getB_image());
			pst.setInt(6, vo.getB_group());
		
			int cnt = pst.executeUpdate();
			if (cnt>0) b=true;
			
			pst.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;		
	}
	public Connection getConn() {
		return conn;
	}


	public void setConn(Connection conn) {
		this.conn = conn;
	}


	public int getListSize() {
		return listSize;
	}


	public void setListSize(int listSize) {
		this.listSize = listSize;
	}


	public int getBlockSize() {
		return blockSize;
	}


	public void setBlockSize(int blockSize) {
		this.blockSize = blockSize;
	}


	public int getTotSize() {
		return totSize;
	}


	public void setTotSize(int totSize) {
		this.totSize = totSize;
	}


	public int getTotPage() {
		return totPage;
	}


	public void setTotPage(int totPage) {
		this.totPage = totPage;
	}


	public int getTotBlock() {
		return totBlock;
	}


	public void setTotBlock(int totBlock) {
		this.totBlock = totBlock;
	}


	public int getNowPage() {
		return nowPage;
	}


	public void setNowPage(int nowPage) {
		this.nowPage = nowPage;
	}


	public int getNowBlock() {
		return nowBlock;
	}


	public void setNowBlock(int nowBlock) {
		this.nowBlock = nowBlock;
	}


	public int getStartNo() {
		return startNo;
	}


	public void setStartNo(int startNo) {
		this.startNo = startNo;
	}


	public int getEndNo() {
		return endNo;
	}


	public void setEndNo(int endNo) {
		this.endNo = endNo;
	}


	public int getStartPage() {
		return startPage;
	}


	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}


	public int getEndPage() {
		return endPage;
	}


	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}

	public static void main(String [] args){
		new B01boardDTO();
	}

}
